package org.jeecg.modules.message.websocket;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.message.model.TerminalStatus;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author scott
 * @Date 2019/11/29 9:41
 * @Description: 此注解相当于设置访问URL
 */
@Component
@Slf4j
@ServerEndpoint("/terminal/{userId}") //此注解相当于设置访问URL
public class TerminalWebSocket {
    private static List<String> webUser = new ArrayList<>();
    private static List<String> terminalUser = new ArrayList<>();

    private String userId;

    /**
     * 缓存 webSocket连接到单机服务class中（整体方案支持集群）
     */
    private static final Map<String, Session> TERMINAL_SESSION_POOL = new HashMap<>();

    private static final Map<String, TerminalStatus> data = new HashMap<>();


    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        try {
            this.userId = userId;
            if (userId.startsWith("web-")) {
                webUser.add(userId);
                TERMINAL_SESSION_POOL.put(userId, session);
                pushMessage(userId);
            } else {
                terminalUser.add(userId);
                data.put(userId, new TerminalStatus());
                TERMINAL_SESSION_POOL.put(userId, session);
                pushMessage();
            }


            log.info("【terminal websocket消息】有新的连接，总数为:" + TERMINAL_SESSION_POOL.size());
        } catch (Exception e) {
            log.info("【terminal websocket消息】创建连接失败");
        }
    }

    @OnClose
    public void onClose() {
        try {
            if (userId.startsWith("web-")) {
                webUser.remove(userId);
            } else {
                terminalUser.remove(userId);
                data.remove(userId);
                pushMessage();
            }
            TERMINAL_SESSION_POOL.remove(userId);
            log.info("【terminal websocket消息】连接断开，总数为:" + TERMINAL_SESSION_POOL.size());
        } catch (Exception e) {
            log.info("【terminal websocket消息】关闭连接失败");
        }
    }

    @OnMessage
    public void onMessage(byte[] bytes) {
        String message = new String(bytes);
        TerminalStatus terminalStatus = JSONUtil.toBean(message, TerminalStatus.class);
        data.put(userId, terminalStatus);
        // log.debug("【websocket消息】收到终端消息:" + message);
        pushMessage();
    }

    private void pushMessage() {
        // log.info("批量发送消息");
        webUser.forEach(ws -> TERMINAL_SESSION_POOL.get(ws).getAsyncRemote().sendText(JSONUtil.toJsonStr(data)));
    }
    private void pushMessage(String userId) {
        // log.info("发送指定消息");
        TERMINAL_SESSION_POOL.get(userId).getAsyncRemote().sendText(JSONUtil.toJsonStr(data));
    }


}